package cn.zzq.aix.nativeinterface.javareflector;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.runtime.ActivityResultListener;
import com.google.appinventor.components.runtime.AndroidNonvisibleComponent;
import com.google.appinventor.components.runtime.AndroidViewComponent;
import com.google.appinventor.components.runtime.ComponentContainer;
import com.google.appinventor.components.runtime.Form;
import com.google.appinventor.components.runtime.OnClearListener;
import com.google.appinventor.components.runtime.collect.Lists;
import com.google.appinventor.components.runtime.util.FileUtil;
import com.google.appinventor.components.runtime.util.MediaUtil;
import com.google.appinventor.components.runtime.util.YailDictionary;
import com.google.appinventor.components.runtime.util.YailList;
import com.google.appinventor.components.runtime.util.YailProcedure;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import cn.zzq.aix.nativeinterface.javareflector.parser.MethodPatternTextParser;
import cn.zzq.aix.nativeinterface.javareflector.parser.ModifiesParser;
import dalvik.system.DexClassLoader;
import gnu.lists.FString;
import gnu.math.Complex;

/*
	Import相关块
	java.lang.Object中的方法块
	类型转换相关块
	获取类及类相关信息块
	构造器相关
	创建对象实例相关块
	获取内部类，内部接口，父类相关块
	Java方法相关块
	java字段相关块
	运行java代码相关块
	包装相关数据代码块
	获取常用对象块
	判断块
	Java数组操作相关块
	Java线程操作相关块
	Activity生命周期相关事件注册器代码块
	JavaReflector常用工具方法块
	类加载器及动态加载dex/so相关块
	常量属性块
	属性块
 */
@SimpleObject
public class JavaReflectorBase extends AndroidNonvisibleComponent {

	public ClassManager classManager;
	// Activity的生命周期事件注册器
	public ActivityListener activityListener;

	public JavaReflectorBase(ComponentContainer container) {
		super(container == null ? null : container.$form());
		Logger.log("构造函数", "开始初始化JavaReflector组件");
		this.classManager = ClassManager.getClassManager(); // 初始化类管理器
		// 向form注册activity的各个事件监听器
		this.activityListener = new ActivityListener(form);

		if (Util.isAndroidEnvironment()) {
			// 在Android环境下将使用Activity的类加载器
			CurrentClassLoader(GetActivityClassLoader());
		} else {
			// 在Java测试环境下将使用Activity的类加载器
			CurrentClassLoader(GetSystemClassLoader());
		}
	}

	/**
	 * 导入类，以便于使用类简称访问类，默认已经导入了java.lang.*下的所有类及子类
	 * 
	 * @param className 类名
	 */
	@SimpleFunction(description = "导入类，以便于使用类简称访问类，默认已经导入了java.lang.*下的所有类及子类")
	public void ImportClass(String className) {
		Logger.log("ImportClass", "开始导入类", className);
		classManager.importClass(className);
	}

	/**
	 * 由用户自定义要导入的类型的名称
	 * 
	 * @param class_ 类对象
	 * @param name   自定义的名称
	 * 
	 */
	@SimpleFunction(description = "由用户自定义要导入的类型的名称")
	public void ImportClassAs(Object class_, String name) {
		Logger.log("ImportClassAs", "导入类", class_, "并重命名", name);
		if (class_ instanceof String || class_ instanceof FString) {
			classManager.importClassAs(class_.toString(), name);
		} else if (class_ instanceof Class<?>) {
			classManager.importClassAs((String) class_, name);
		} else {
			throw new ReflectException(class_, "ImportClassAs", "不支持的导入");
		}
	}

	/**
	 * 获得对象的hash值
	 * 
	 * @param object 对象
	 * @return hash值
	 */
	@SimpleFunction(description = "获得对象的hash值,如果为null则返回-1")
	public int GetHashCode(Object object) {
		int hashCode = object == null ? -1 : object.hashCode();
		return hashCode;
	}

	/**
	 * 判断两个对象是否相等
	 * 
	 * @param object1 对象1
	 * @param object2 对象2
	 * @return 是否相等
	 */
	@SimpleFunction(description = "判断两个对象是否相等")
	public boolean IsEqual(Object object1, Object object2) {
		boolean result = ReflectUtil.isEqual(object1, object2);
		return result;
	}

	/**
	 * 返回一个对象的字符串表示(将调用对象内部的toString方法)
	 * 
	 * @param object 一个对象
	 * @return 该对象的字符串表示
	 */
	@SimpleFunction(description = "返回一个对象的字符串表示(将调用对象内部的toString方法,如果为null，则返回null文本)")
	public String ToString(Object object) {
		String result = ReflectUtil.toString(object);
		return result;
	}

	/**
	 * 将一个对象强制转换成此 Class 对象所表示的类或接口。
	 * 
	 * @param object 对象
	 * @param class_ 类或接口
	 * @return 转换后的对象
	 */
	@SimpleFunction(description = "将一个对象强制转换成此 Class 对象所表示的类或接口。")
	public Object Cast(Object object, Object class_) {
		class_ = classManager.parseAsClass(class_);
		Object result = ((Class<?>) class_).cast(object);
		return result;
	}

	/**
	 * 通过名称获取一个Type/Class对象 该名称可以是 1.已经导入的class对象
	 * (java.lang.*下的所有类，以及调用ImportClass导入后的class对象的类名简称与自定义的名称)，
	 * 2.基本数据类型int,byte,boolean,short,long,double,float,void
	 * 3.数组数据类型，使用int[],byte[]，Object[]等创建表示一维数组的类，使用int[][],byte[][],Object[][]等创建表示二维数组的类，以此类推
	 * 
	 * @param name 类名，类简称，自定义名称，基本数据类型名，数组名
	 * @return 类型对象
	 */
	@SimpleFunction(description = "通过名称获取一个Type/Class对象 该名称可以是 \n" + "	 * 1.已经导入的class对象\n"
			+ "	 * (java.lang.*下的所有类，以及调用ImportClass导入后的class对象的类名简称与自定义的名称)，\n"
			+ "	 * 2.基本数据类型int,byte,boolean,short,long,double,float,void\n"
			+ "	 * 3.数组数据类型，使用int[],byte[]，Object[]等创建表示一维数组的类，使用int[][],byte[][],Object[][]等创建表示二维数组的类，以此类推\n"
			+ "	 * ")
	public Object GetClassByName(String name) {
		Logger.log("GetClassByName", "尝试通过类型名称", name, "获取类型");
		try {
			Class<?> class_ = classManager.get(name);
			Logger.log("GetClassByName", "根据名称", name, "查找到了类型", class_);
			return class_;
		} catch (ClassNotFoundException e) {
			throw new ReflectException(name, "GetClassByName", e);
		}

	}

	/**
	 * 获取一个类的类全名
	 * 
	 * @param class_ 类对象或者某对象
	 * @return 类全名
	 */
	@SimpleFunction(description = "获取一个类的类全名")
	public String GetClassName(Object class_) {
		class_ = classManager.parseAsClass(class_);
		String className = ((Class<?>) class_).getName();
		return className;
	}

	/**
	 * 获取一个类的类简称
	 * 
	 * @param class_ 类对象或者某对象
	 * @return 类简称
	 */
	@SimpleFunction(description = "获取一个类的类简称")
	public String GetClassSimpleName(Object class_) {
		class_ = classManager.parseAsClass(class_);
		String result = ((Class<?>) class_).getSimpleName();
		return result;
	}

	/**
	 * 获取表示传入的对象的类对象
	 * 
	 * @param object 需要传入的对象
	 * @return 表示该对象的类的对象
	 */
	@SimpleFunction(description = "获取表示传入的对象的类对象")
	public Object GetClassByObject(Object object) {
		Class<?> class_ = ReflectUtil.getClassByObject(object);
		Logger.log("GetClassByObject", "成功获取表示对象", object, "的类", class_);
		return class_;
	}

	/**
	 * 用过滤器过滤一个类的所有构造器并返回过滤后的构造器列表
	 * 
	 * @param class_ 类
	 * @param filter 过滤器
	 * @return 构造器列表
	 */
	@SimpleFunction(description = "获取参数匹配的构造器（构造函数）")
	public YailList GetConstructorsWithFilter(Object class_, final YailProcedure filter) {
		class_ = classManager.parseAsClass(class_);
		Set<Constructor<?>> allConstructor = ReflectUtil.getConstructors((Class<?>) class_);
		Set<Constructor<?>> filteredConstructor = ReflectUtil.getFilteredConstructors(allConstructor,
				new ReflectUtil.ConstructorFilter() {

					@Override
					public boolean accept(Constructor<?> constructor) {
						return (boolean) filter.call(constructor);
					}
				});
		return YailList.makeList(filteredConstructor);
	}

	/**
	 * 获取一个类中的所有构造器
	 * 
	 * @param class_ 类
	 * @return 构造器列表
	 */
	@SimpleFunction(description = "获取一个类中的所有构造器")
	public YailList GetConstructors(Object class_) {
		class_ = classManager.parseAsClass(class_);
		return YailList.makeList(ReflectUtil.getConstructors((Class<?>) class_));
	}

	/**
	 * 根据指定参数类型列表获得此 Class 对象所表示的类的公共构造方法
	 * 
	 * @param class_         class对象
	 * @param parameterTypes 参数类型列表
	 * @return 此 Class 对象所表示的类的公共构造方法
	 */
	@SimpleFunction(description = "根据指定参数类型列表获得此 Class 对象所表示的类的公共构造方法")
	public Object GetConstructor(Object class_, YailList parameterTypes) {
		class_ = classManager.parseAsClass(class_);
		try {
			return ReflectUtil.getConstructor((Class<?>) class_, Util.list2Classes(parameterTypes));
		} catch (Exception e) {
			throw new ReflectException(class_, "GetConstructor", e);
		}
	}

	/**
	 * 用字符串获取此 Class 对象所表示的类的公共构造方法
	 * 
	 * @param pattern 字符串格式为 类名称<参数类型字符串>，例如java.lang.StringBuffer<int>
	 * @return 此 Class 对象所表示的类的公共构造方法
	 */
	@SimpleFunction(description = "用代码获取此 Class 对象所表示的类的公共构造方法" + "代码格式为 类名称<参数类型字符串>，例如java.lang.StringBuffer<int>")
	public Object GetConstructorByPattern(String pattern) {
		try {
			return TextReflectUtil.getConstructorByPattern(pattern);
		} catch (Exception e) {
			// 可能出現类型转换异常或者找不到构造器异常
			throw new ReflectException(pattern, "GetConstructorByPattern", e);
		}
	}

	@SimpleFunction(description = "获取一个构造器的所有参数")
	public YailList GetConstuctorParameters(Object constuctor) {
		return YailList.makeList(((Constructor<?>) constuctor).getParameters());
	}

	/**
	 * 获取构造器对象的参数列表
	 * 
	 * @param constructor 构造器对象
	 * @return 该构造器对象的参数类型列表
	 */
	@SimpleFunction(description = "获取构造器对象的参数列表")
	public YailList GetConstructorParameterTypes(Object constructor) {
		constructor = Util.parseAsConstructor(constructor);
		return YailList.makeList(((Constructor<?>) constructor).getParameterTypes());
	}

	@SimpleFunction(description = "根据默认的构造器创建一个对象实例")
	public Object CreateInstance(Object class_) {
		class_ = classManager.parseAsClass(class_);
		try {
			Object result = ((Class<?>) class_).newInstance();
			Logger.log("类", class_, "的实例创建成功,实例对象为", result);
			return result;
		} catch (Exception e) {
			throw new ReflectException(class_, "CreateInstance");
		}
	}

	@SimpleFunction(description = "根据指定的构造器创建一个对象实例")
	public Object CreateInstanceByConstructor(Object constructor, final YailList parameters) {
		final Constructor<?> mConstructor = Util.parseAsConstructor(constructor);
		try {
			YailList formatedParameters = FormatList(parameters, GetConstructorParameterTypes(constructor));
			return ReflectUtil.createInstanceByConstructor((Constructor<?>) mConstructor, formatedParameters.toArray(),
					new ReflectUtil.ExceptionCallback() {
						@Override
						public void catchException(Throwable exception) {
							throw new ReflectException(new Object[] { mConstructor, parameters },
									"CreateInstanceByConstructor", exception, "你需要使用InvodeMethodCallback来捕获异常");
						}
					});
		} catch (Exception e) {
			throw new ReflectException(new Object[] { constructor, parameters }, "CreateInstanceByConstructor", e);
		}
	}

	@SimpleFunction(description = "根据指定的构造器创建一个对象实例")
	public void CreateInstanceByConstructorCallback(Object constructor, YailList parameters,
			YailProcedure createdCallback, final YailProcedure exceptionCallback) {
		constructor = Util.parseAsConstructor(constructor);

		YailList parameterTypes = GetConstructorParameterTypes(constructor);
		Object result = ReflectUtil.createInstanceByConstructor((Constructor<?>) constructor,
				FormatList(parameters, parameterTypes).toArray(),

				new ReflectUtil.ExceptionCallback() {

					@Override
					public void catchException(Throwable exception) {
						exceptionCallback.call(exception);
					}
				});

		if (result != null) {
			createdCallback.call(result);
		}

	}

	/**
	 * 根据函数列表或函数方法创建接口
	 * 
	 * @param interfaceClass   接口类
	 * @param methodListOrDict 方法列表或方法字典
	 * @return 创建出的接口对象
	 */
	@SimpleFunction(description = "根据函数列表或函数方法创建接口")
	public Object CreateInstanceFromInterface(Object interfaceClasses, Object methodsList) {
		try {

			if (interfaceClasses instanceof YailList) {
				// 如果interfaceClasses为列表，则转换为Class数组
				interfaceClasses = Util.list2Classes((YailList) interfaceClasses);

			} else if (interfaceClasses instanceof String || interfaceClasses instanceof FString) {
				// 如果interfaceClasses为用逗号分割的类型文本，解析为Class数组
				interfaceClasses = TextReflectUtil.getTypesByText(interfaceClasses.toString());
			} else if (interfaceClasses instanceof Class<?>) {
				// 如果interfaceClasses仅为一个单独的Class对象，那么直接构造为数组
				interfaceClasses = new Class<?>[] { classManager.parseAsClass(interfaceClasses) };
			} else {
				throw new ReflectException(interfaceClasses, "CreateInstanceFromInterface",
						"interfaceClasses传入参数类型不规范");
			}
		} catch (ClassNotFoundException e) {
			throw new ReflectException(interfaceClasses, "CreateInstanceFromInterface", "接口列表中存在文本形式的接口，但是找不到这个接口", e);
		}

		if (methodsList instanceof YailList) {
			return createInstanceFromInterface((Class<?>[]) interfaceClasses, (YailList) methodsList);
		} else if (methodsList instanceof YailDictionary) {
			return createInstanceFromInterface((Class<?>[]) interfaceClasses, (YailDictionary) methodsList);
		} else {
			throw new ReflectException(new Object[] { interfaceClasses, methodsList }, "CreateInstanceFromInterface",
					"methodsList参数类型错误");
		}
	}

	/**
	 * 使用函数字典创建接口
	 * 
	 * @param interfaceClasses 接口类对象或接口名
	 * @param methodDict       接口方法字典，{方法名1:匿名函数1,方法名1:匿名函数1, ... ,方法名n:,匿名函数n}
	 * @return 代理后的接口对象
	 */
	private static Object createInstanceFromInterface(final Class<?>[] interfaceClasses,
			final YailDictionary methodDict) {
		return ReflectUtil.createInstanceFromInterface(ClassManager.classLoader, interfaceClasses, methodDict);
	}

	/**
	 * 创建接口
	 * 
	 * @param interfaceClass 接口类对象或接口名
	 * @param methodList     接口列表，按照单层列表[方法名1,匿名函数1,方法名2,匿名函数2, ... ,方法名n,匿名函数n],
	 *                       或者双层列表[[方法名1,匿名函数1],[方法名1,匿名函数1], ...
	 *                       ,[方法名n,匿名函数n]]进行排列
	 * @return 代理后的接口对象
	 */
	private static Object createInstanceFromInterface(final Class<?>[] interfaceClasses, YailList methodsList) {

		if (methodsList.getObject(0) instanceof YailList) {
			return createInstanceFromInterface(interfaceClasses, YailDictionary.alistToDict(methodsList));
		} else {
			return createInstanceFromInterface(interfaceClasses, single2Double(methodsList));

		}
	}

	// 单层列表按照12，34，56，78，...分组为双层列表
	private static YailList single2Double(YailList singleList) {
		ArrayList<YailList> pairList = Lists.newArrayList();

		@SuppressWarnings("unchecked")
		Iterator<Object> it = singleList.iterator();

		it.next();// 消除*list*
		while (it.hasNext()) {
			Object pairKey = it.next();
			if (it.hasNext()) {
				Object pairValue = it.next();
				pairList.add(YailList.makeList(new Object[] { pairKey, pairValue }));
			}
		}
		return YailList.makeList(pairList);
	}

	@SimpleFunction(description = "获取指定类中的所有内部类")
	public YailList GetInnerClasses(Object class_) {
		class_ = classManager.parseAsClass(class_);
		return YailList.makeList(ReflectUtil.getInnerClasses((Class<?>) class_));
	}

	@SimpleFunction(description = "获取类中的所有内部接口")
	public YailList GetInnerInterfaces(Object class_) {
		class_ = classManager.parseAsClass(class_);
		return YailList.makeList(((Class<?>) class_).getInterfaces());
	}

	@SimpleFunction(description = "获取一个类的父类")
	public Object GetSuperClass(Object class_) {
		class_ = classManager.parseAsClass(class_);
		return ((Class<?>) class_).getSuperclass();
	}

	@SimpleFunction(description = "按照给定的匿名函数过滤获取方法列表")
	public YailList GetMethodsWithFilter(Object class_, final YailProcedure filter) {
		class_ = classManager.parseAsClass(class_);
		return YailList.makeList(ReflectUtil.getFilteredMethods(ReflectUtil.getMethods((Class<?>) class_),
				new ReflectUtil.MethodFilter() {

					@Override
					public boolean accept(Method method) {
						return (boolean) filter.call(method);
					}
				}));
	}

	@SimpleFunction(description = "获取该类及其父类的所有方法")
	public YailList GetMethods(Object class_) {
		class_ = classManager.parseAsClass(class_);
		return YailList.makeList(ReflectUtil.getMethods((Class<?>) class_));
	}

	/**
	 * @param pattern 形如[类型名].[方法名]<类型名1,类型名2>，例如java.lang.StringBuffer.append<boolean>
	 * @return
	 */
	@SimpleFunction(description = "按照类名或已导入的类简称.方法名<类型文本>获取一个方法对象")
	public Object GetMethodByPattern(String pattern) {
		try {
			return TextReflectUtil.getMethodByPattern(pattern);
		} catch (Exception e) {
			throw new ReflectException(pattern, "GetMethodByText", e);
		}
	}

	@SimpleFunction(description = "获取一个方法的参数列表")
	public YailList GetMethodParameters(Object method) {
		method = Util.parseAsMethod(method);
		return YailList.makeList(((Method) method).getParameters());
	}

	@SimpleFunction(description = "获取一个参数的类型")
	public Object GetParameterType(Object parameter) {
		return ((Parameter) parameter).getType();
	}

	/**
	 * 获取参数对象的名称
	 * 
	 * @param parameter 参数对象
	 * @return 该参数对象的名称
	 */
	@SimpleFunction(description = "获取参数对象的名称")
	public String GetParameterName(Object parameter) {
		return ((Parameter) parameter).getName();
	}

	/**
	 * 获取方法参数类型列表
	 * 
	 * @param method 方法对象
	 * @return 该方法的参数类型列表
	 */
	@SimpleFunction(description = "获取方法参数类型列表")
	public YailList GetMethodParameterTypes(Object method) {
		method = Util.parseAsMethod(method);
		return YailList.makeList(((Method) method).getParameterTypes());
	}

	@SimpleFunction(description = "获取类中参数匹配的public方法对象（包括父类）")
	public Object GetMethod(Object class_, String name, YailList parameterTypes) {
		class_ = classManager.parseAsClass(class_);
		try {
			return ReflectUtil.getMethod((Class<?>) class_, name, Util.list2Classes(parameterTypes));
		} catch (Exception e) {
			throw new ReflectException(class_, "GetMethod", e);
		}
	}

	@SimpleFunction(description = "获取方法名")
	public String GetMethodName(Object method) {
		method = Util.parseAsMethod(method);
		return ((Method) method).getName();
	}

	@SimpleFunction(description = "")
	public YailList GetFields(Object class_) {
		class_ = classManager.parseAsClass(class_);
		return YailList.makeList(ReflectUtil.getFields((Class<?>) class_));
	}

	/**
	 * 获取一个类中的常量表，以字典键值对返回
	 * 
	 * @param class_ 类
	 * @return 字典
	 */
	@SimpleFunction(description = "获取一个类中的所有常量，以字典键值对返回")
	public YailDictionary GetConstantDict(Object class_) {
		class_ = classManager.parseAsClass(class_);
		if (class_ instanceof String || class_ instanceof FString) {
			class_ = GetClassByName(class_.toString());
		}
		return ReflectUtil.getConstantMap((Class<?>) class_);
	}

	/**
	 * 获取某个类中的所有字段的字段名
	 * 
	 * @param class_ 某个类
	 * @return 字段名列表
	 */
	@SimpleFunction(description = "")
	public YailList GetFieldNames(Object class_) {
		class_ = classManager.parseAsClass(class_);
		return YailList.makeList(ReflectUtil.getFieldNames((Class<?>) class_));
	}

	@SimpleFunction(description = "获取类中名称匹配的public字段对象（包括父类）")
	public Object GetField(Object class_, String name) throws NoSuchFieldException {
		class_ = classManager.parseAsClass(class_);
		return ReflectUtil.getField((Class<?>) class_, name);

	}

	@SimpleFunction(description = "获取某对象的字段的值")
	public Object GetFieldValue(Object object, Object field) {
		try {
			if (field != null) {
				SetAccessible(field, true);
			}
			return ((Field) field).get(object);
		} catch (Exception exception) {
			throw new ReflectException(new Object[] { object, field }, "GetFieldValue", exception);
		}
	}

	@SimpleFunction(description = "设置某对象字段的值")
	public void SetFieldValue(Object object, Object field, Object value) {
		if (field != null) {
			SetAccessible(field, true);
		}
		try {
			value = formatElement(value, (Class<?>) GetFieldType(field));
			((Field) field).set(object, value);
		} catch (Exception e) {
			throw new ReflectException(new Object[] { object, field, value }, "SetFieldValue", e);
		}
	}

	@SimpleFunction(description = "根据字段名称获取某对象的字段值")
	public Object GetFieldValueByObject(Object object, String fieldName) {
		try {
			return GetFieldValue(object, GetField(GetClassByObject(object), fieldName));
		} catch (NoSuchFieldException e) {
			throw new ReflectException(new Object[] { object, fieldName }, "GetFieldValueByObject", e);
		}
	}

	@SimpleFunction(description = "设置一个字段的值")
	public void SetFieldValueByObject(Object object, String fieldName, Object value) {
		try {
			SetFieldValue(object, GetField(GetClassByObject(object), fieldName), value);
		} catch (NoSuchFieldException e) {
			throw new ReflectException(new Object[] { object, fieldName, value }, "SetFieldValueByObject", e);
		}
	}

	@SimpleFunction(description = "设置对象的可访问能力")
	public void SetAccessible(Object accessibleObject, boolean flag) {
		((AccessibleObject) accessibleObject).setAccessible(flag);
	}

	@SimpleFunction(description = "获取某类的静态字段的值")
	public Object GetStaticFieldValueByClass(Object class_, String fieldName) {
		class_ = classManager.parseAsClass(class_);
		try {
			return GetFieldValue(null, GetField(class_, fieldName));
		} catch (NoSuchFieldException e) {
			throw new ReflectException(new Object[] { class_, fieldName }, "GetStaticFieldValueByClass", e);
		}
	}

	@SimpleFunction(description = "设置静态字段的值")
	public void SetStaticFieldValueByClass(Object class_, String fieldName, Object value) {
		class_ = classManager.parseAsClass(class_);
		try {
			SetFieldValue(null, GetField(class_, fieldName), value);
		} catch (NoSuchFieldException e) {
			throw new ReflectException(new Object[] { class_, fieldName, value }, "SetStaticFieldValueByClass", e);
		}
	}

	@SimpleFunction(description = "获取字段名")
	public String GetFieldName(Object field) {
		return ((Field) field).getName();
	}

	@SimpleFunction(description = "获取字段类对象")
	public Object GetFieldType(Object field) {
		return ((Field) field).getType();
	}

	@SimpleFunction(description = "获取可视组件的View")
	public Object GetVisibleComponentView(AndroidViewComponent visibleComponent) {
		return visibleComponent.getView();
	}

	@SimpleFunction(description="获取一个可修饰对象(类，方法，参数，字段)的修饰符列表")
	public YailList GetModifies(Object modifiable) {
		return YailList.makeList(new ModifiesParser(modifiable));
	}
	
	/**
	 * 执行一个Java方法，注意此方法无法进行java异常的捕获，如果此块引发异常，程序将报错，如果想要捕获异s常，则需要调用InvokeMethodCallback
	 * 
	 * @param instance   java对象实例
	 * @param method     java方法对象
	 * @param parameters 参数列表
	 * @return 执行该java方法的返回值
	 */
	@SimpleFunction(description = "运行java方法，假如该方法是静态方法，instance接NULL，parameters 为调用方法的参数列表")
	public Object InvokeMethod(final Object instance, Object method, YailList parameters) {
		Logger.log("InvokeMethod", "尝试执行对象", instance, "的方法", method, "使用参数", parameters);
		if (method instanceof String || method instanceof FString) {
			// 默认访问方法应当使用[类名].[方法名]<参数类型1,参数类型2,...>
			// 如果不包含.，将自动补全表示实例的类
			MethodPatternTextParser mptp = new MethodPatternTextParser(method.toString());

			if (mptp.getClassName().isEmpty()) {
				method = instance.getClass().getName().concat(".").concat(method.toString());
			}

		}

		// 使方法转换为方法对象
		final Method method1 = Util.parseAsMethod(method);

		YailList typeList = GetMethodParameterTypes(method);

		try {
			Object result = ReflectUtil.invokeMethod(instance, method1, FormatList(parameters, typeList).toArray(),
					new ReflectUtil.ExceptionCallback() {
						@Override
						public void catchException(Throwable exception) {
							throw new ReflectException(new Object[] { method1, instance }, "InvokeMethod", exception,
									"你执行的方法抛出了一个异常，需要使用InvodeMethodCallback来捕获异常");
						}
					});
			Logger.log("InvokeMethod", "执行对象", instance, "的方法", method, "使用参数", parameters, "成功，执行结果：", result);
			return result;
		} catch (IllegalAccessException e) {
			throw new ReflectException(new Object[] { method1, instance }, "InvokeMethod", e,
					"无法调用该方法对象，该方法可能非公开，请使用SetAccessible该方法为true来强制调用该方法");
		}

	}

	/**
	 * 调用静态java方法
	 * 
	 * @param method     静态java方法对象
	 * @param parameters 参数列表
	 * @return 运行该静态java方法的结果
	 */
	@SimpleFunction(description = "调用静态办法，参见 InvokeMethod")
	public Object InvokeStaticMethod(Object method, YailList parameters) {
		method = Util.parseAsMethod(method);
		Object result = InvokeMethod(null, method, parameters);
		return result;
	}

	@SimpleFunction(description = "调用静态办法，参见 InvokeMethodCallback")
	public void InvokeStaticMethodCallback(Object method, YailList parameters, YailProcedure invokedCallback,
			YailProcedure exceptionCallback) {
		method = Util.parseAsMethod(method);
		InvokeMethodCallback(null, method, parameters, invokedCallback, exceptionCallback);
	}

	@SimpleFunction(description = "运行java方法，假如该方法是静态方法，instance接NULL\n" + "parameters 为调用方法的参数列表\n"
			+ "invokedCallback为调用成功的回调函数，有一个参数接收调用结果\n" + "exceptionCallback为捕获异常的回调函数，有一个参数接收(Exception)对象")
	public void InvokeMethodCallback(final Object instance, Object method, final YailList parameters,
			final YailProcedure invokedCallback, final YailProcedure exceptionCallback) {
		if (method instanceof String || method instanceof FString) {
			if (!method.toString().contains(".")) {
				method = instance.getClass().getName().concat(".").concat(method.toString());
			}
		}
		final Method method1 = Util.parseAsMethod(method);
		YailList typeList = GetMethodParameterTypes(method);

		try {
			Object result = ReflectUtil.invokeMethod(instance, method1, FormatList(parameters, typeList).toArray(),
					new ReflectUtil.ExceptionCallback() {
						@Override
						public void catchException(Throwable exception) {
							exceptionCallback.call(exception);
						}
					});
			Logger.log("InvokeMethodCallback", "执行对象", instance, "的方法", method, "使用参数", parameters, "成功，执行结果：", result);
			if (invokedCallback != null && result != null) {
				invokedCallback.call(result);
			}
		} catch (IllegalAccessException e) {
			throw new ReflectException(new Object[] { method1, instance }, "InvokeMethod", e,
					"无法调用该方法对象，该方法可能非公开，请使用SetAccessible该方法为true来强制调用该方法");
		}

	}

	/**
	 * 构造char类型的数据，可传入以下数据值 1.字符串/文本 2.整数 3.char数据 4.包装后的Charactor数据
	 * 
	 * @param charData 原始的char数据
	 * @return 构造后的char类型数据
	 */
	@SimpleFunction(description = "构造char类型的数据，可传入以下数据值 1.字符串/文本 2.整数 3.char数据 4.包装后的Charactor数据")
	public Object BuildChar(Object charData) {
		return Util.buildChar(charData);
	}

	/**
	 * 获取当前屏幕所在的Activity/Form（同时也是当前屏幕的Context）
	 * 
	 * @return 当前屏幕所在的Form
	 */
	@SimpleFunction(description = "获取当前屏幕所在的Activity/Form（同时也是当前屏幕的Context）")
	public Object GetForm() {
		return form;
	}

	/**
	 * 获取当前屏幕所在的Context（同时也是当前屏幕的Activity/Form）
	 * 
	 * @return 当前屏幕所在的Context
	 */
	@SimpleFunction(description = "获取当前屏幕所在的Context（同时也是当前屏幕的Activity/Form）")
	public Object GetContext() {
		return form.getApplicationContext();
	}

	/**
	 * 判断当前运行环境是否为ai伴侣
	 * 
	 * @return 当前运行环境是否为ai伴侣
	 */
	@SimpleFunction(description = "判断当前运行环境是否为ai伴侣")
	public boolean IsAICompanion() {
		return Util.isAICompanion();
	}

	@SimpleFunction(description = "判断一个实例对象是否是这个类的实例,相当于instanceof")
	public boolean IsInstance(Object class_, Object object) {
		class_ = classManager.parseAsClass(class_);
		return ((Class<?>) class_).isInstance(object);
	}

	@SimpleFunction(description = "判定指定的 Class 对象是否表示一个接口类型。")
	public boolean IsInterface(Object class_) {
		class_ = classManager.parseAsClass(class_);
		return ((Class<?>) class_).isInterface();
	}

	/*--------数组操作相关块---------*/
	@SimpleFunction(description = "判断传入的对象是否为一个数组")
	public boolean Array_IsArray(Object object) {
		return ArrayUtil.isArray(object);
	}

	@SimpleFunction(description = "将java数组转换为json字符串")
	public String Array_toJSON(Object array) {
		return ArrayUtil.array2json(array);
	}

	@SimpleFunction(description = "Java数组转AI列表")
	public YailList Array_Array2List(Object array) {
		return ArrayUtil.array2List(array);
	}

	@SimpleFunction(description = "AI列表转Java数组")
	public Object Array_List2Array(YailList list, Object elementType) {
		return ArrayUtil.list2Array(list, (Type) elementType);
	}

	@SimpleFunction(description = "AI列表转Java数组")
	public Object Array_List2BooleanArray(YailList list) {
		return ArrayUtil.list2BooleanArray(list);
	}

	@SimpleFunction(description = "AI列表转Java数组")
	public Object Array_List2ByteArray(YailList list) {
		return ArrayUtil.list2ByteArray(list);
	}

	@SimpleFunction(description = "AI列表转Java数组")
	public Object Array_List2CharArray(YailList list) {
		return ArrayUtil.list2CharArray(list);
	}

	@SimpleFunction(description = "AI列表转Java数组")
	public Object Array_List2FloatArray(YailList list) {
		return ArrayUtil.list2FloatArray(list);
	}

	@SimpleFunction(description = "AI列表转Java数组")
	public Object Array_List2IntArray(YailList list) {
		return ArrayUtil.list2IntArray(list);
	}

	@SimpleFunction(description = "AI列表转Java数组")
	public Object Array_List2LongArray(YailList list) {
		return ArrayUtil.list2LongArray(list);
	}

	@SimpleFunction(description = "AI列表转Java数组")
	public Object Array_List2ShortArray(YailList list) {
		return ArrayUtil.list2ShortArray(list);
	}

	@SimpleFunction(description = "返回指定数组对象中对应索引的值。")
	public Object Array_Get(Object array, int index) {
		return Array.get(array, index);
	}

	@SimpleFunction(description = "以 boolean 形式返回指定数组对象中索引组件的值。")
	public boolean Array_GetBoolean(Object array, int index) {
		return Array.getBoolean(array, index);
	}

	@SimpleFunction(description = "以 byte 形式返回指定数组对象中索引组件的值。")
	public byte Array_GetByte(Object array, int index) {
		return Array.getByte(array, index);
	}

	@SimpleFunction(description = "以 char 形式返回指定数组对象中索引组件的值。")
	public Object Array_GetChar(Object array, int index) {
		return Array.getChar(array, index);
	}

	@SimpleFunction(description = "以 double 形式返回指定数组对象中索引组件的值。")
	public double Array_GetDouble(Object array, int index) {
		return Array.getDouble(array, index);
	}

	@SimpleFunction(description = "以 float 形式返回指定数组对象中索引组件的值。")
	public float Array_GetFloat(Object array, int index) {
		return Array.getFloat(array, index);
	}

	@SimpleFunction(description = "以 int 形式返回指定数组对象中索引组件的值。")
	public int Array_GetInt(Object array, int index) {
		return Array.getInt(array, index);
	}

	@SimpleFunction(description = "以 long 形式返回指定数组对象中索引组件的值。")
	public long Array_GetLong(Object array, int index) {
		return Array.getLong(array, index);
	}

	@SimpleFunction(description = "以 short 形式返回指定数组对象中索引组件的值。")
	public short Array_GetShort(Object array, int index) {
		return Array.getShort(array, index);
	}

	@SimpleFunction(description = "将指定数组对象中索引组件的值设置为指定的新值。")
	public void Array_Set(Object array, int index, Object value) {
		Array.set(array, index, value);
	}

	@SimpleFunction(description = "将指定数组对象中索引组件的值设置为指定的 boolean 值。")
	public void Array_SetBoolean(Object array, int index, boolean value) {
		Array.setBoolean(array, index, value);
	}

	@SimpleFunction(description = "将指定数组对象中索引组件的值设置为指定的 byte 值。")
	public void Array_SetByte(Object array, int index, byte value) {
		Array.setByte(array, index, value);
	}

	@SimpleFunction(description = "将指定数组对象中索引组件的值设置为指定的 char 值。")
	public void Array_SetChar(Object array, int index, Object value) {
		Array.setChar(array, index, (char) BuildChar(value));
	}

	@SimpleFunction(description = "将指定数组对象中索引组件的值设置为指定的 double 值。")
	public void Array_SetDouble(Object array, int index, double value) {
		Array.setDouble(array, index, value);
	}

	@SimpleFunction(description = "将指定数组对象中索引组件的值设置为指定的 float 值。")
	public void Array_SetFloat(Object array, int index, float value) {
		Array.setFloat(array, index, value);
	}

	@SimpleFunction(description = "将指定数组对象中索引组件的值设置为指定的 int 值。")
	public void Array_SetInt(Object array, int index, int value) {
		Array.setInt(array, index, value);
	}

	@SimpleFunction(description = "将指定数组对象中索引组件的值设置为指定的 long 值。")
	public void Array_SetLong(Object array, int index, long value) {
		Array.setLong(array, index, value);
	}

	@SimpleFunction(description = "将指定数组对象中索引组件的值设置为指定的 short 值。")
	public void Array_SetShort(Object array, int index, short value) {
		Array.setShort(array, index, value);
	}

	@SimpleFunction(description = "返回指定数组对象的长度。")
	public int Array_GetLength(Object array) {
		return Array.getLength(array);
	}

	@SimpleFunction(description = "获取组成数组类的类")
	public Object Array_GetElementType(Object arrayClass) {
		return ((Class<?>) arrayClass).getComponentType();
	}

	@SimpleFunction(description = "根据元素类型构造一个指定维度的数组类型")
	public Object Array_BuildArrayType(Object elementType, int dimension) {
		return ArrayUtil.buildArrayType((Type) elementType, dimension);
	}

	/**
	 * 根据数组的维度列表创建一个数组实例
	 * 
	 * @param elementType    数组元素类型
	 * @param dimensionsList 数组维度列表
	 * @return
	 */
	@SimpleFunction(description = "创建一个具有指定的元素类型和维度的新数组。dimensionsList为数组维度列表，\n"
			+ "如数组[[1,2],[3,4],[4,5]]可表示为（长度为2的数组）的数组长度为3，即array[2][3]，\n" + "所以创建一个如上述的多维数组dimensionsList须传入列表(2,3)")
	public Object Array_CreateInstanceByDimensions(Object elementType, YailList dimensionsList) {

		return ArrayUtil.createInstanceByDimensions(classManager.parseAsClass(elementType), dimensionsList);
	}

	/**
	 * 根据数组长度构造一个空数组
	 * 
	 * @param elementType 数组元素类型
	 * @param length      数组长度
	 * @return 数组对象
	 */
	@SimpleFunction(description = "根据数组长度构造一个空数组")
	public Object Array_CreateInstanceByLength(Object elementType, int length) {
		return Array.newInstance(classManager.parseAsClass(elementType), length);
	}

	@SimpleFunction(description = "创建一个线程")
	public Object Thread_CreateInstance(final YailProcedure function) {
		return new Thread(new Runnable() {
			@Override
			public void run() {
				function.call();
			}
		});
	}

	@SimpleFunction(description = "获取当前所在的线程")
	public Object Thread_CurrentThread() {
		return Thread.currentThread();
	}

	@SimpleFunction(description = "该线程的中断标志位")
	public boolean Thread_IsInterrupted(Object thread) {
		return ((Thread) thread).isInterrupted();
	}

	@SimpleFunction(description = "使该线程的中断标志置为true")
	public void Thread_Interrupted(Object thread) {
		((Thread) thread).interrupt();
	}

	@SimpleFunction(description = "sleep方法,使当前线程阻塞millis毫秒")
	public void Thread_Sleep(long millis) {
		try {
			Thread.sleep(millis);
		} catch (InterruptedException e) {
			throw new ReflectException(millis, "Thread_Sleep", e);
		}
	}

	@SimpleFunction(description = "开始运行这个线程")
	public void Thread_Start(Object thread) {
		((Thread) thread).start();
	}

	@SimpleFunction(description = "设置线程的名称")
	public void Thread_SetName(Object thread, String name) {
		((Thread) thread).setName(name);
	}

	@SimpleFunction(description = "获取线程的名称")
	public String Thread_GetName(Object thread) {
		return ((Thread) thread).getName();
	}

	@SimpleFunction(description = "使当前线程从执行状态（运行状态）变为可执行态（就绪状态），" + "为同一个优先级的线程让位，但是让位时间不确定。" + "cpu会从众多的可执行态里选择，也就是说，"
			+ "当前也就是刚刚的那个线程还是有可能会被再次执行到的，" + "并不是说一定会执行其他线程而该线程在下一次中不会执行到了。")
	public static void Thread_Yield() {
		Thread.yield();
	}

	@SimpleFunction(description = "当线程被创建时就会生成一个id值作为该线程的特征之一")
	public static long Thread_GetID(Object thread) {
		return ((Thread) thread).getId();
	}

	@SimpleFunction(description = "优先级被划分为1-10,1最低10最高。优先级越高的线程被分配时间片的机会越多，那么被CPU执行的机会就越多。默认是5")
	public static void Thread_SetPriority(Object thread, int priority) {
		((Thread) thread).setPriority(priority);
	}

	@SimpleFunction(description = "优先级被划分为1-10,1最低10最高。优先级越高的线程被分配时间片的机会越多，那么被CPU执行的机会就越多。默认是5")
	public static int Thread_GetPriority(Object thread) {
		return ((Thread) thread).getPriority();
	}

	@SimpleFunction(description = "把指定的线程加入到当前线程中，可以将两个交替执行的线程合并为顺序执行的线程。\n"
			+ "比如在B线程中执行线程A的join方法，a.join(),那么B线程就会暂停执行，先等A线程执行完毕，B线程再重新进入可运行状态。\n" + "\n"
			+ "join方法中还可以设置时间a.join(1000),这样就让A执行规定时间。默认为0\n")
	public static void Thread_Join(Object thread, long millis) {
		try {
			((Thread) thread).join(millis);
		} catch (InterruptedException e) {
			throw new ReflectException(new Object[] { thread, millis }, "Thread_Join", e);
		}
	}

	@SimpleFunction(description = "当activity收到结果时回调")
	public int RegisterForActivityResult(final YailProcedure listener) {
		ActivityResultListener activityResultListener = new ActivityResultListener() {

			@Override
			public void resultReturned(int requestCode, int resultCode, Intent data) {
				listener.call(requestCode, resultCode, data);
			}
		};
		activityListener.activityResultMap.put(listener, activityResultListener);
		return form.registerForActivityResult(activityResultListener);
	}

	@SimpleFunction(description = "注册相应的事件监听")
	public void RegisterForActivityResultByRequestCode(final YailProcedure listener, int requestCode) {
		ActivityResultListener activityResultListener = new ActivityResultListener() {

			@Override
			public void resultReturned(int requestCode, int resultCode, Intent data) {
				listener.call(requestCode, resultCode, data);
			}
		};
		activityListener.activityResultMap.put(listener, activityResultListener);
		form.registerForActivityResult(activityResultListener, requestCode);
	}

	@SimpleFunction(description = "取消相应回调")
	public void UnregisterForActivityResult(YailProcedure listener) {
		form.unregisterForActivityResult(activityListener.activityResultMap.get(listener));
	}

	@SimpleFunction(description = "当AI伴侣刷新时回调")
	public void RegisterForOnClear(YailProcedure listener) {
		activityListener.onClearListeners.add(listener);
	}

	// 获取当前屏幕所在的Context（同时也是当前屏幕的Activity/Form）
	@SimpleFunction(description = "当屏幕被销毁时回调")
	public void RegisterForOnDestroy(YailProcedure listener) {
		activityListener.onDestroyListeners.add(listener);
	}

	@SimpleFunction(description = "当屏幕初始化时回调")
	public void RegisterForOnInitialize(YailProcedure listener) {
		activityListener.onInitializeListeners.add(listener);
	}

	@SimpleFunction(description = "当屏幕被启动时回调")
	public void RegisterForOnNewIntent(YailProcedure listener) {
		activityListener.onNewIntentListeners.add(listener);
	}

	@SimpleFunction(description = "当创建标题栏菜单时回调")
	public void RegisterForOnCreateOptionsMenu(YailProcedure listener) {
		activityListener.onCreateOptionsMenuListeners.add(listener);
	}

	@SimpleFunction(description = "当标题栏菜单被选中时回调")
	public void RegisterForOnOptionsItemSelected(YailProcedure listener) {
		activityListener.onOptionsItemSelectedListeners.add(listener);
	}

	@SimpleFunction(description = "当屏幕不可见时回调")
	public void RegisterForOnPause(YailProcedure listener) {
		activityListener.onPauseListeners.add(listener);
	}

	@SimpleFunction(description = "当屏幕重新可见时回调")
	public void RegisterForOnResume(YailProcedure listener) {
		activityListener.onResumeListeners.add(listener);
	}

	@SimpleFunction(description = "当屏幕被终止时回调")
	public void RegisterForOnStop(YailProcedure listener) {
		activityListener.onStopListeners.add(listener);
	}

	@SimpleFunction(description = "取消相应的回调")
	public void UnregisterForOnClear(YailProcedure listener) {
		activityListener.onClearListeners.remove(listener);
	}

	@SimpleFunction(description = "取消相应的回调")
	public void UnregisterForOnCreateOptionsMenu(YailProcedure listener) {
		activityListener.onCreateOptionsMenuListeners.remove(listener);
	}

	@SimpleFunction(description = "取消相应的回调")
	public void UnregisterForOnDestroy(YailProcedure listener) {
		activityListener.onDestroyListeners.remove(listener);
	}

	@SimpleFunction(description = "取消相应的回调")
	public void UnregisterForOnInitialize(YailProcedure listener) {
		activityListener.onInitializeListeners.remove(listener);
	}

	@SimpleFunction(description = "取消相应的回调")
	public void UnregisterForOnNewIntent(YailProcedure listener) {
		activityListener.onNewIntentListeners.remove(listener);
	}

	@SimpleFunction(description = "取消相应的回调")
	public void UnregisterForOnOptionsItemSelected(YailProcedure listener) {
		activityListener.onOptionsItemSelectedListeners.remove(listener);
	}

	@SimpleFunction(description = "取消相应的回调")
	public void UnregisterForOnPause(YailProcedure listener) {
		activityListener.onPauseListeners.remove(listener);
	}

	@SimpleFunction(description = "取消相应的回调")
	public void UnregisterForOnResume(YailProcedure listener) {
		activityListener.onResumeListeners.remove(listener);
	}

	@SimpleFunction(description = "取消相应的回调")
	public void UnregisterForOnStop(YailProcedure listener) {
		activityListener.onStopListeners.remove(listener);
	}

	@SimpleFunction(description = "按照类型列表格式化参数列表中的数据")
	public YailList FormatList(YailList parameters, Object types) {
		if (types instanceof YailList) {
			return formatList(parameters, (YailList) types);
		} else {
			try {
				return FormatList(parameters, TextReflectUtil.getTypesByText(types.toString()));
			} catch (ClassNotFoundException e) {
				throw new ReflectException(new Object[] { parameters, types }, "FormatList", "解析类型文本异常");
			}
		}
	}

	private static YailList formatList(YailList parameters, YailList types) {
		if (parameters.size() == types.size()) {
			Object[] parameterArray = parameters.toArray();
			for (int i = 0; i < types.size(); i++) {
				Class<?> type = (Class<?>) types.getObject(i);
				parameterArray[i] = formatElement(parameterArray[i], type);
			}
			return YailList.makeList(parameterArray);
		} else {
			throw new ReflectException(new Object[] { parameters, types }, "formatList", "参数列表和类型列表长度不一致");
		}
	}

	private static Object formatElement(Object element, Class<?> type) {
		if (element instanceof Complex) {
			// 若参数为ai数字
			element = NumberUtil.AINumber2JavaNumber((Complex) element, type);
		} else if (element instanceof String || element instanceof FString) {
			element = NumberUtil.parseAsJavaNumber(element.toString(), type);
		}
		return element;
	}

	@SimpleFunction(description = "将除素材外的ai路径转换为java中可用的绝对路径")
	public static String ToAbsolutePath(String path) {
		return Util.parseAsAbsolutePath(path);
	}

	@SimpleFunction(description = "获取素材文件，网络文件，存储卡文件，根目录文件，应用数据文件等输入流")
	public void GetInputStreamCallback(String path, YailProcedure gotCallback, YailProcedure exceptionCallback) {
		try {
			if (path.startsWith("//")) {
				gotCallback.call(MediaUtil.openMedia(form, path));
			} else {
				gotCallback.call(MediaUtil.openMedia(form, ToAbsolutePath(path)));
			}

		} catch (IOException e) {
			if (exceptionCallback != null) {
				exceptionCallback.call(e);
			} else {
				throw new ReflectException(path, "发生了io异常", e);
			}
		}
	}

	@SimpleFunction(description = "获取素材文件，网络文件，存储卡文件，根目录文件，应用数据文件等输入流")
	public Object GetInputStream(String path) {
		try {
			if (path.startsWith("//")) {
				return MediaUtil.openMedia(form, path);
			} else {
				return MediaUtil.openMedia(form, ToAbsolutePath(path));
			}
		} catch (IOException e) {
			throw new ReflectException(path, "GetInputStream", e, "发生了IO异常，请调用GetInputStream来捕获异常");
		}
	}

	@SimpleFunction(description = "获取加载Activity/Screen的类加载器")
	public static Object GetActivityClassLoader() {
		return Form.class.getClassLoader();
	}

	@SimpleFunction(description = "获取系统类加载器")
	public static Object GetSystemClassLoader() {
		return ClassLoader.getSystemClassLoader();
	}

	@SimpleFunction(description = "获取一个类加载器的父类加载器")
	public static Object GetParentClassLoader(Object classLoader) {
		return ((ClassLoader) classLoader).getParent();
	}

	@SimpleFunction(description = "获取某个类的类加载器")
	public Object GetClassLoader(Object class_) {
		class_ = classManager.parseAsClass(class_);
		return ((Class<?>) class_).getClassLoader();
	}

	@SimpleFunction(description = "为要运行的代码加锁")
	public static void SynchronizedRunner(Object lock, YailProcedure codeFargment) {
		synchronized (lock) {
			codeFargment.call();
		}
	}

	@SimpleFunction(description = "在UI线程运行一个匿名函数")
	public void RunOnUiThread(final YailProcedure codeFragment) {
		form.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				codeFragment.call();
			}
		});
	}

	@SimpleFunction(description = "加载dex文件并获得其类加载器")
	public static Object LoadDex(String dexFile, Object parentClassLoader) {
		String soOutput = Form.getActiveForm().getDir("so", Context.MODE_PRIVATE).getAbsolutePath();
		if (parentClassLoader == null) {
			// 如果未指明父类加载器，那么就用Activity的类加载器作为默认父类加载器
			parentClassLoader = Form.class.getClassLoader();
		}
		DexClassLoader dexClassloader = null;
		String dexOutput = Form.getActiveForm().getDir("dexes", Context.MODE_PRIVATE).getAbsolutePath();
		if (dexFile.startsWith("/sdcard") || dexFile.startsWith("~/")) {
			dexFile = ToAbsolutePath(dexFile); // 将ai路径格式转化为通用路径格式
			File oriDexFile = new File(dexFile);
			if (oriDexFile.exists() && oriDexFile.isFile()) {
				if (dexFile.endsWith(".jar")) {
					dexClassloader = new DexClassLoader(dexFile, dexOutput, soOutput, (ClassLoader) parentClassLoader);
				} else if (dexFile.endsWith(".dex")) {
					try {
						dexOutput += "/" + oriDexFile.getName();
						FileUtil.copyFile(dexFile, dexOutput);
						dexClassloader = new DexClassLoader(dexOutput, null, soOutput, (ClassLoader) parentClassLoader);
					} catch (IOException e) {
						throw new ReflectException(new String[] { dexFile, dexOutput }, "LoadDex", e, "发生io异常");
					}
				} else {
					throw new ReflectException(dexFile, "LoadDex", "不是一个有效的dex文件");
				}
			} else {
				throw new ReflectException(dexFile, "LoadDex", "dex文件不存在");
			}
		} else if (dexFile.startsWith("//")) {
			// 这是一个资源文件
			try {
				InputStream is = MediaUtil.openMedia(Form.getActiveForm(), dexFile);
				if (dexFile.endsWith(".jar")) {
					String cache = Form.getActiveForm().getCacheDir().getAbsoluteFile() + dexFile.substring(1);
					FileUtil.writeStreamToFile(is, cache);
					dexClassloader = new DexClassLoader(cache, dexOutput, soOutput, (ClassLoader) parentClassLoader);
				} else if (dexFile.endsWith(".dex")) {
					dexOutput += dexFile.substring(1);
					FileUtil.writeStreamToFile(is, dexOutput);
					dexClassloader = new DexClassLoader(dexOutput, null, soOutput, (ClassLoader) parentClassLoader);
				}
			} catch (IOException e) {
				throw new ReflectException(new String[] { dexFile, dexOutput }, "LoadDex", e, "发生io异常");
			}

		}
		return dexClassloader;
	}

	@SimpleFunction(description = "将so文件放置进应用程序数据目录以便与dex动态加载so库,其中libraryName必须省略开头的lib与结尾的.so")
	public static String CopySoFile(String soFile, String libraryName) {
		String soOutput = "";
		if (libraryName.startsWith("lib") && libraryName.endsWith(".so")) {
			soOutput = Form.getActiveForm().getDir("so", Context.MODE_PRIVATE).getAbsolutePath() + "/" + libraryName;
		} else {
			soOutput = Form.getActiveForm().getDir("so", Context.MODE_PRIVATE).getAbsolutePath() + "/lib" + libraryName
					+ ".so";
		}
		if (soFile.startsWith("/sdcard") || soFile.startsWith("~/")) {
			soFile = ToAbsolutePath(soFile); // 将ai路径格式转化为通用路径格式
			File oriSoFile = new File(soFile);
			if (oriSoFile.exists() && oriSoFile.isFile()) {
				try {
					FileUtil.copyFile(soFile, soOutput);
					// error = loadNativeLibrary(new File(soOutput), (ClassLoader) classLoader);
				} catch (Exception e) {
					throw new ReflectException(new String[] { soFile, soOutput }, "LoadSo", e);
				}

			} else {
				throw new ReflectException(soFile, "LoadSo", "so文件不存在");
			}
		} else if (soFile.startsWith("//")) {
			try {
				InputStream is = MediaUtil.openMedia(Form.getActiveForm(), soFile);
				FileUtil.writeStreamToFile(is, soOutput);
				// error = loadNativeLibrary(new File(soOutput), (ClassLoader) classLoader);
			} catch (Exception e) {
				throw new ReflectException(new String[] { soFile, soOutput }, "LoadSo", e);
			}
		}
		return soOutput;
	}

	private Logcater logcater = null;

	@SimpleFunction(description = "启用Logcat监听")
	public void StartLogcat(final YailProcedure logcatCallback) {
		StopLogcat();
		logcater = new Logcater();
		logcater.setLogcatListener(new LogcatListener() {
			@Override
			public void logcat(String log) {
				logcatCallback.call(log);
			}
		});
		form.registerForOnClear(new OnClearListener() {

			@Override
			public void onClear() {
				logcater.stopLogcat();
			}
		});
		logcater.startLogcat();
	}

	@SimpleFunction(description = "停止Logcat的监听")
	public void StopLogcat() {
		if (logcater != null) {
			logcater.stopLogcat();
		}
	}

	/**
	 * 获取当前平台的SDK版本号
	 * 
	 * @return
	 */
	@SimpleProperty(description = "获取当前平台的SDK版本号")
	public static int SDK_INT() {
		return Build.VERSION.SDK_INT;
	}

	@SuppressWarnings("deprecation")
	@SimpleProperty(description = "获取当前平台的SDK版本号")
	public static String CPU_ABI() {
		return Build.CPU_ABI;
	}

	@SuppressWarnings("deprecation")
	@SimpleProperty(description = "获取当前平台的CPU架构")
	public static String CPU_ABI2() {
		return Build.CPU_ABI2;
	}

	/**
	 * 空值
	 * 
	 * @return null
	 */
	@SimpleProperty(description = "null值")
	public static Object NULL() {
		return null;
	}

	@SimpleProperty(description = "获取当前应用程序的包名")
	public String PackageName() {
		return form.getPackageName();
	}

	/**
	 * double基本数据类型
	 * 
	 * @return double基本数据类型
	 */
	@SimpleProperty(description = "double基本数据类型")
	public static Object DoubleType() {
		return double.class;
	}

	/**
	 * int基本数据类型
	 * 
	 * @return int基本数据类型
	 */
	@SimpleProperty(description = "int基本数据类型")
	public static Object IntType() {
		return int.class;
	}

	/**
	 * char基本数据类型
	 * 
	 * @return char基本数据类型
	 */

	@SimpleProperty(description = "char基本数据类型")
	public static Object CharType() {
		return char.class;
	}

	/**
	 * short基本数据类型
	 * 
	 * @return short基本数据类型
	 */
	@SimpleProperty(description = "short基本数据类型")
	public static Object ShortType() {
		return short.class;
	}

	/**
	 * boolean基本数据类型
	 * 
	 * @return boolean基本数据类型
	 */
	@SimpleProperty(description = "boolean基本数据类型")
	public static Object BooleanType() {
		return boolean.class;
	}

	/**
	 * long基本数据类型
	 * 
	 * @return long基本数据类型
	 */
	@SimpleProperty(description = "long基本数据类型")
	public static Object LongType() {
		return Long.TYPE;
	}

	/**
	 * byte基本数据类型
	 * 
	 * @return byte基本数据类型
	 */
	@SimpleProperty(description = "byte基本数据类型")
	public static Object ByteType() {
		return byte.class;
	}

	/**
	 * float基本数据类型
	 * 
	 * @return float基本数据类型
	 */
	@SimpleProperty(description = "float基本数据类型")
	public static Object FloatType() {
		return float.class;
	}

	/**
	 * void基本数据类型
	 * 
	 * @return void基本数据类型
	 */
	@SimpleProperty(description = "void基本数据类型")
	public static Object VoidType() {
		return void.class;
	}

	/**
	 * 获得一个java.lang.String类的类类型
	 * 
	 * @return java.lang.String类的类类型
	 */
	@SimpleProperty(description = "获得一个java.lang.String类的类类型")
	public static Object StringType() {
		return String.class;
	}

	@SimpleProperty(description = "获取当前JavaReflector的类加载器")
	public static Object CurrentClassLoader() {
		return ClassManager.classLoader;
	}

	@SimpleProperty(description = "替换JavaReflector的默认类加载器")
	public static void CurrentClassLoader(Object classLoader) {
		ClassManager.classLoader = (ClassLoader) classLoader;
	}

	@SimpleProperty(description = "当类被加载时是否初始化该类(赋值静态成员变量，执行静态代码块)")
	public static boolean InitializeOnClassLoaded() {
		return ClassManager.initializeOnClassLoaded;
	}

	@SimpleProperty(description = "指定当类被加载时是否初始化该类(赋值静态成员变量，执行静态代码块)")
	public static void InitializeOnClassLoaded(boolean initialize) {
		ClassManager.initializeOnClassLoaded = initialize;
	}

	@SimpleProperty(description = "是否启用debug模式")
	public static void DebugMode(boolean mode) {
		Logger.debugMode = mode;
	}

	@SimpleProperty(description = "是否启用debug模式")
	public static boolean DebugMode() {
		return Logger.debugMode;
	}
}
